package com.iflytek.iot.okhttp.config;

import com.iflytek.iot.common.net.SSLSocketFactoryBuilder;
import com.iflytek.iot.common.net.TrustAnyTrustManager;
import com.iflytek.iot.common.utils.StringUtils;
import okhttp3.ConnectionPool;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.net.Proxy;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author yu 2019/8/5.
 */
@Configuration
public class OkHttpConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpConfiguration.class);

    @Resource
    private ConnectionPool connectionPool;

    @Resource
    private OkHttpConfigProperties okHttpConfigProperties;

    @Resource
    private Proxy proxy;

    /**
     * 创建httpclient
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(name = "okHttpClient")
    public OkHttpClient okHttpClient() {
        return createHttpClient(this.connectionPool, null, okHttpConfigProperties);
    }

    /**
     * 代理模式的OHttpClient
     *
     * @return
     */
    @Bean(name = "proxyOkHttpClient")
    @ConditionalOnMissingBean(name = "proxyOkHttpClient")
    public OkHttpClient proxyOkHttpClient() {
        boolean usedProxy = okHttpConfigProperties.getProxy().getEnable();
        if (usedProxy) {
            return createHttpClient(connectionPool, proxy, okHttpConfigProperties);
        }
        return createHttpClient(this.connectionPool, null, okHttpConfigProperties);
    }

    /**
     * 创建OkHttpClient
     *
     * @param connectionPool 连接池
     * @param proxy          代理对象
     * @param environment
     * @return
     */
    private OkHttpClient createHttpClient(ConnectionPool connectionPool, Proxy proxy, OkHttpConfigProperties okHttpConfigProperties) {
        long connectTimeout = okHttpConfigProperties.getConnectTimeout();
        long readTimeout = okHttpConfigProperties.getReadTimeout();
        long writeTimeout = okHttpConfigProperties.getWriteTimeout();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(SSLSocketFactoryBuilder.getSslSocketFactory(), new TrustAnyTrustManager())
                .retryOnConnectionFailure(false)
                .connectionPool(connectionPool)
                .hostnameVerifier((s, sslSession) -> true)
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTimeout, TimeUnit.MILLISECONDS);
        if (Objects.nonNull(proxy)) {
            LOGGER.debug("building proxy for REST connection -> address is {}", proxy.address().toString());
            builder.proxy(proxy);
            String userName = okHttpConfigProperties.getProxy().getUsername();
            String password = okHttpConfigProperties.getProxy().getPassword();
            if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)) {
                builder.proxyAuthenticator((route, response) -> {
                    //设置代理服务器账号密码
                    String credential = Credentials.basic(userName, password);
                    return response.request().newBuilder()
                            .header("Proxy-Authorization", credential)
                            .build();
                });
            }
        }
        return builder.build();
    }
}
